﻿using System;
using System.Text.Json;

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Distributed;

namespace MyAspireApp.ApiService.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private readonly IDistributedCache _cache;
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        public WeatherForecastController(IDistributedCache cache)
        {
            _cache = cache;
        }

        [HttpPut]
        public async Task<ActionResult<IEnumerable<WeatherForecast>>> Put()
        {
            // 缓存键
            string cacheKey = "WeatherForecasts";

            // 尝试从缓存获取数据
            byte[]? cachedData = await _cache.GetAsync(cacheKey);

            if (cachedData != null)
            {
                // 缓存命中，反序列化数据
                var forecasts = JsonSerializer.Deserialize<IEnumerable<WeatherForecast>>(cachedData);
                return Ok(forecasts);
            }

            // 缓存未命中，生成新数据
            var newForecasts = Enumerable.Range(1, 5).Select(index => new WeatherForecast
        (
            DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
            Random.Shared.Next(-20, 55),
            Summaries[Random.Shared.Next(Summaries.Length)]
        ))
            .ToArray();

            // 设置缓存选项
            var cacheOptions = new DistributedCacheEntryOptions
            {
                AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5),
                SlidingExpiration = TimeSpan.FromMinutes(1)
            };

            // 序列化并存储到缓存
            byte[] serializedData = JsonSerializer.SerializeToUtf8Bytes(newForecasts);
            await _cache.SetAsync(cacheKey, serializedData, cacheOptions);

            return Ok(newForecasts);
        }
    }
}
